const socketIO = require('socket.io');
const jwt = require('jsonwebtoken');
const jwtConfig = require('../config/jwt');
const { User } = require('../models');

class SocketService {
  constructor(server) {
    this.io = socketIO(server, {
      cors: {
        origin: "*",
        methods: ["GET", "POST"]
      }
    });

    this.initEvents();
  }

  initEvents() {
    this.io.use(async (socket, next) => {
      try {
        // JWT认证
        const token = socket.handshake.auth.token;
        if (!token) throw new Error('Authentication error');

        const decoded = jwt.verify(token, jwtConfig.secret);
        const user = await User.findByPk(decoded.userId);

        if (!user) throw new Error('User not found');

        socket.user = user;
        next();
      } catch (err) {
        next(new Error('Authentication failed'));
      }
    });

    this.io.on('connection', (socket) => {
      console.log(`用户连接: ${socket.user.username} (${socket.id})`);

      // 加入用户专属房间
      socket.join(`user_${socket.user.id}`);

      // 加入聊天室
      socket.on('join_room', (roomId) => {
        socket.join(roomId);
        console.log(`${socket.user.username} 加入了房间 ${roomId}`);
      });

      // 离开聊天室
      socket.on('leave_room', (roomId) => {
        socket.leave(roomId);
        console.log(`${socket.user.username} 离开了房间 ${roomId}`);
      });

      // 断开连接
      socket.on('disconnect', () => {
        console.log(`用户断开: ${socket.user.username}`);
      });
    });
  }

  // 向指定房间广播消息
  broadcastToRoom(roomId, event, data) {
    this.io.to(roomId).emit(event, data);
  }

  // 向指定用户发送消息
  sendToUser(userId, event, data) {
    this.io.to(`user_${userId}`).emit(event, data);
  }
}

module.exports = SocketService;